package org.epam.szhuk.greenway.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.location.Location;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public final class TextWriter {
	private TextWriter(){
		
	}
	
	private static final String TAG="TextWriter";
	private static final String newLine = System.getProperty("line.separator");
	
	public static void writeToFile(Context context, Location loc, Preferences prefs, String filename) throws IOException{
        String extStorageState = Environment.getExternalStorageState();
		if (extStorageState.equals(Environment.MEDIA_MOUNTED)){
			String folderPath=Environment.getExternalStorageDirectory() +  File.separator +prefs.getAppFilesFolder();
			File folderCheck = new File(folderPath);  
			if(!folderCheck.exists()){
				folderCheck.mkdir();
			}
			//Date date = new Date();
			//int filenameStart=videoFilePath.lastIndexOf(File.separator)+1;
			//int filenameEnd=videoFilePath.lastIndexOf(".");
			//String videoFileName=new String(videoFilePath.substring(filenameStart, filenameEnd));
			
			File file = new File(folderPath+File.separator  + filename);
			if(!file.exists()){
				file.createNewFile();
			}
			FileWriter fileWritter = new FileWriter(folderPath+File.separator  + filename ,true);
			BufferedWriter bufferWritter = new BufferedWriter(fileWritter);

			//information about current position and speed
	        Date date = new Date(loc.getTime());
	        SimpleDateFormat sdf = new SimpleDateFormat(Preferences.DATE_WRITETOFILE_FORMAT);
	        
	        int latE6=(int) (loc.getLatitude()*1E6);
	        int lonE6=(int)(loc.getLongitude()*1E6);
	        String locationTime = sdf.format(date);
	        bufferWritter.write(new String(locationTime+", "+latE6+", "+lonE6+", "+loc.getSpeed() +newLine).toCharArray());
	        bufferWritter.close();
		}
		else{//External storage unavailable
			myToast(context, "External storage unavailiable, can't log location data");
			Log.e(TAG,"External storage unavailiable, can't log location data");
		}
	}
	

	private static void myToast(Context context, String text){
		Toast.makeText(context, text, Toast.LENGTH_LONG).show();
	}
}
